<?php
/**
 * 成员管理类
 * Created by PhpStorm.
 * User: zd
 * Date: 2018/10/17
 * Time: 09:54
 */

namespace app\api\controller\v1;

use app\api\model\WorkUser;
use \app\api\service\Token;
use app\api\service\WorkContact;
use app\api\validate\BatchMemberParameter;
use app\api\validate\MemberParameter;
use app\api\validate\WorkIDMustBePositiveInt;
use app\api\validate\WorkMemberAdd;
use app\api\service\Enterprise;
use app\api\validate\WorkMemberDeleteParameter;
use app\api\validate\WorkMemberDepartmentParameter;
use app\api\validate\WorkMemberDtail;
use app\api\validate\WorkMemberParameter;
use app\lib\exception\SuccessMessage;
use app\lib\exception\WorkMemberException;

class Member extends ThirdApp
{
    protected $beforeActionList=[
        'checkPrimaryScope' => ['only'=>'getMemberList,addMember'],
    ];
    /**
     * 获取成员列表
     * @param null $d_id
     * @return \think\response\Json
     * @throws WorkMemberException
     */
    public function getMemberList(){
        $uid = Token::getCurrentUid();
        $contact = new WorkContact();
        $result = $contact->getMemberList($uid,$d_id=null);
        if ($result->isEmpty()){
            throw new WorkMemberException([
                'code'=>404,
                'msg'=>"成员不存在",
                'error_code'=>43003
            ]);
        }else{
            return json($result,201);
        }
    }

    /**
     * 获取部门成员列表
     * @param null $d_id
     * @return \think\response\Json
     * @throws WorkMemberException
     * @throws \think\Exception
     */
    public function getDepartmentUser($d_id=null){
        (new WorkIDMustBePositiveInt())->goCheck();
        $uid = Token::getCurrentUid();
        $contact = new WorkContact();
        $result = $contact->getMemberList($uid,$d_id);
        if ($result->isEmpty()){
            throw new WorkMemberException([
                'code'=>203,
                'msg'=>"成员不存在",
                'error_code'=>43003
            ]);
        }else{
            return json($result,201);
        }
    }

    /**
     * 获取成员详情
     * @param $userId
     * @return \think\response\Json
     * @throws WorkMemberException
     * @throws \think\Exception
     */
    public function getMemberByID($userId){
        (new WorkMemberDtail())->goCheck();
        $uid = Token::getCurrentUid();
        $contact = new WorkContact();
        $userInfo =  $contact->getUserById($uid,$userId);
        if (!$userInfo){
            throw new WorkMemberException([
                'code'=>404,
                'msg'=>"成员不存在",
                'error_code'=>43003
            ]);
        }else{
            $leader = [];
            $list = $userInfo->toArray();
            foreach($list['departments'] as $key=>$value){
                $arr[$value['d_id']] = $value['name'];
                if($value['pivot']['isleader'] == 1){
                    $leader[$value['d_id']] = $value['name'];
                }
            }
            $list['department'] = $arr;
            $list['leader'] = $leader;
            unset($list['departments']);
            return json($list,201);
        }
    }

    /**
     * 创建成员
     * @return \think\response\Json
     * @throws WorkMemberException
     * @throws \app\lib\exception\ParameterException
     * @throws \think\Exception
     */
    public function addMember(){
        $validate = new WorkMemberAdd();
        $validate->goCheck();
        $dataArray = $validate->getDataByRule(input('post.'));
        $uid = Token::getCurrentUid();
        $contact = new WorkContact();
       $result = $contact->addMember($uid,$dataArray);
        if (is_array($result)){
            throw new WorkMemberException([
                'code'=>203,
                'msg'=>json_decode('{'.$result[1],true),
                'error_code'=>43002
            ]);
        }else{
            return json(new SuccessMessage(),201);
        }
    }
    /**
     * 更新用户头像
     * @param $wu_id
     * @return \think\response\Json
     */
    public function updateUserImg($wu_id){
        $t_id = Token::getCurrentUid();
        $service = new Enterprise();
        $dataArray = input('post.');
        $result = $service->updateImg($dataArray,$wu_id);
        if (!empty($result)){
            //清空缓存
            $tag = sprintf(config('cache.card_base'),$wu_id);//缓存key
            $this->removeCache($tag);
            $data['code'] = 200;
            $data['content'] = $result;
        }else{
            $data['code'] = 2002;
            $data['content'] = '';
        }
        return json($data);
    }

    /**
     * 更新成员信息
     * @return \think\response\Json
     * @throws WorkMemberException
     * @throws \app\lib\exception\ParameterException
     * @throws \think\Exception
     */
    public function updateMember(){
        $validate = new WorkMemberParameter();
        $validate->goCheck();
        $dataArray = $validate->getDataByRule(input('post.'));
        $uid = Token::getCurrentUid();
        $contact = new WorkContact();
        $result = $contact->updateMember($uid,$dataArray);
        if (is_array($result)){
            throw new WorkMemberException([
                'code'=>203,
                'msg'=>json_decode('{'.$result[1],true),
                'error_code'=>43003
            ]);
        }else{
            return json(new SuccessMessage(),201);
        }
    }

    /**
     * 更新部门成员信息
     * @param $userId
     * @return \think\response\Json
     * @throws WorkMemberException
     * @throws \think\Exception
     */
    public function updateUserDepartment($userId){
        $validate = new  WorkMemberDepartmentParameter();
        $validate->goCheck();
        $dataArray = input('post.');
        $uid = Token::getCurrentUid();
        $contact = new WorkContact();
        $userInfo =  WorkUser::getUserByID($uid,$userId);
        $result = $contact->updateUserDepartment($uid,$userInfo,$dataArray);
        if (is_array($result)){
            throw new WorkMemberException([
                'code'=>400,
                'msg'=>$result,
                'error_code'=>43004
            ]);
        }else{
            return json(new SuccessMessage(),201);
        }
    }

    /**
     * 删除成员
     * @return \think\response\Json
     * @throws WorkMemberException
     * @throws \app\lib\exception\ParameterException
     * @throws \think\Exception
     */
    public function deleteMember(){
        $validate = new WorkMemberDeleteParameter();
        $validate->goCheck();
        $dataArray = $validate->getDataByRule(input('post.'));
        $uid = Token::getCurrentUid();
        $contact = new WorkContact();
        $result = $contact->deleteMember($uid,$dataArray['userId']);
        if (is_array($result)){
            throw new WorkMemberException([
                'code'=>200,
                'msg'=>$result,
                'error_code'=>43005
            ]);
        }else{
            return json(new SuccessMessage(),201);
        }
    }

    /**
     * 同步信息
     * @return int
     */
    public function syncUser(){
        $t_id = Token::getCurrentUid();
        $contact = new WorkContact();
        $result = $contact->syncUser($t_id);
        return $result;
    }

    /**
     * 名片授权
     * @param $type
     * @param $info
     * @param $wu_id
     * @return \think\response\Json
     * @throws WorkMemberException
     * @throws \app\lib\exception\UserException
     * @throws \think\Exception
     */
    public function memberAuthorize($type,$info,$wu_id){
        (new MemberParameter())->goCheck();
        $t_id = Token::getCurrentUid();
        $contact = new WorkContact();
        $result =  $contact->memberAuthorize($t_id,$type,$info,$wu_id);
        if (empty($result)){
            throw new WorkMemberException([
                'code'=>200,
                'msg'=>"授权失败",
                'error_code'=>43006
            ]);
        }
        return json(new SuccessMessage(),201);
    }

    /**
     * 用户批量开通名片
     * @param $type
     * @param $info
     * @param $list
     * @return \think\response\Json
     * @throws WorkMemberException
     * @throws \think\Exception
     */
    public function batchAuthorize($type,$info,$list){
        (new BatchMemberParameter())->goCheck();
        $uid = Token::getCurrentUid();
        $contact = new WorkContact();
        $result =  $contact->batchMemberAuthorize($type,$info,$list);
        if (empty($result)){
            throw new WorkMemberException([
                'code'=>200,
                'msg'=>"授权失败",
                'error_code'=>43006
            ]);
        }
        return json(new SuccessMessage(),201);
    }
    /**
     * 授权状态
     * @return \think\response\Json
     * @throws WorkMemberException
     */
    public function authorizeStatus(){
        $t_id = Token::getCurrentUid();
        $contact = new WorkContact();
        $result = $contact->authorizeStatus($t_id);
        if (empty($result)){
            throw new WorkMemberException([
                'code'=>200,
                'msg'=>"获取授权状态失败",
                'error_code'=>43009
            ]);
        }
        return json($result);
    }

    /**
     * 批量关闭名片
     * @param $type
     * @param $info
     * @param $list
     * @return \think\response\Json
     * @throws WorkMemberException
     * @throws \think\Exception
     */
    public function batchCancelAuthorize($type,$info,$list){
        (new BatchMemberParameter())->goCheck();
        $uid = Token::getCurrentUid();
        $contact = new WorkContact();
        $result =  $contact->batchMemberAuthorize($type,$info,$list);
        if (empty($result)){
            throw new WorkMemberException([
                'code'=>200,
                'msg'=>"授权失败",
                'error_code'=>43008
            ]);
        }
        return json(new SuccessMessage(),201);
    }

    /**
     * 获取用户数量
     * @param $id
     * @return \think\response\Json
     * @throws WorkMemberException
     */
    public function getCustomerNum($id,$type){
        //(new IDMustBePositiveInt())->goCheck();
        $t_id = Token::getCurrentUid();
        $contact = new WorkContact();
        $result =  $contact->getCustomerNum($id,$type);
        if (is_array($result)){
            $data = $result;
        }else{
            $data['num'] = $result;
        }
        return json($data);
    }

    /**
     * 用户交接结果
     * @param $handoverId
     * @param $receiverId
     * @return array
     */
    public function getCustomerResult($handoverId,$receiverId){
        $t_id = Token::getCurrentUid();//身份验证
        $contact = new WorkContact();
        $result =  $contact->getCustomerResult($handoverId,$receiverId);
        return json($result);
    }

    /**
     * 用户交接
     * @param $beforeId
     * @param $endId
     * @return \think\response\Json
     * @throws WorkMemberException
     */
    public function handoverUser($beforeId,$endId,$num){
        $uid = Token::getCurrentUid();
        $contact = new WorkContact();
        $result =  $contact->handoverUser($beforeId,$endId,$num);
        if (!$result){
            throw new WorkMemberException([
                'code'=>200,
                'msg'=>"交接失败",
                'error_code'=>43007
            ]);
        }
        return json(new SuccessMessage(),201);
    }
}